package ge.telasi.tasks.ui.search;

import ge.telasi.tasks.model.User;
import ge.telasi.tasks.search.Condition;
import ge.telasi.tasks.ui.UIUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.Icon;

/**
 * User(s) field.
 * 
 * @author dimitri
 */
public class UserField extends Field {
    private List<User> users;

    public UserField(String name, String humanName) {
        super(name, humanName);
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
    
    @Override
    public String getType() {
        return "user";
    }

    @Override
    public Icon getIcon() {
        return UIUtils.getIcon16x16("user.png");
    }

    @Override
    public Condition getCondition() {
        // empty condition
        if (users == null || users.isEmpty()) {
            return null;
        }

        // create where condition
        StringBuilder b = new StringBuilder();
        Map<String, Object> subst = new HashMap<String, Object>();
        b.append(" ( ");
        b.append(getSysName());
            b.append(" IN ( ");
        boolean first = true;
        for (User user : users) {
            if (!first) {
                b.append(", ");
            }
            String fieldName = getNextField();
            b.append(":");
            b.append(fieldName);
            subst.put(fieldName, user.getId());
            first = false;
        }
        b.append(" ) ) ");
        String where = b.toString();

        // build condition
        Condition condition = new Condition();
        condition.setCondition(where);
        condition.getSubstitutions().putAll(subst);
        return condition;
    }

}